from PIL import Image, ImageDraw, ImageFont
import os

'''
图片处理模块 
'''
class ImageProcessor:
    @staticmethod
    def mark_dimension(image, dimension_label, position=(20, 20), font_size=20):
        """在图片上标注尺寸标号"""
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype("arial.ttf", font_size)
        draw.text(position, dimension_label, fill="black", font=font)
        return image
        
    @staticmethod
    def resize_image(image, max_width=1024, max_height=768):
        """调整图片大小"""
        width, height = image.size
        ratio = min(max_width / width, max_height / height)
        new_size = (int(width * ratio), int(height * ratio))
        return image.resize(new_size, Image.LANCZOS)
        
    @staticmethod
    def save_image(image, output_path, format="PNG"):
        """保存图片"""
        image.save(output_path, format=format)
        print(f"Image saved to {output_path}")
        
    @staticmethod
    def batch_process_images(input_dir, output_dir, processor_func):
        """批量处理图片"""
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
            
        for filename in os.listdir(input_dir):
            if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
                input_path = os.path.join(input_dir, filename)
                output_path = os.path.join(output_dir, filename)
                
                try:
                    with Image.open(input_path) as img:
                        processed_img = processor_func(img)
                        processed_img.save(output_path)
                except Exception as e:
                    print(f"Error processing {filename}: {e}")